<?php

/**
 * Terminal Test
 * php .\bitcoin.php getTransactionByHash b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da
 * php .\bitcoin.php getTransactionByAddress 3A3bfM8Zg4aEa6sLEMtj4NaTDsgE5FKpoQ
 */
$arg1 = $argv[1];
$arg2 = $argv[2];

switch ($arg1) {
    case "getTransactionByHash":
        // b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da
        $transaction = getTransactionByHash($arg2);
        var_dump($transaction);
    break;
    case "getTransactionByAddress":
        // 3A3bfM8Zg4aEa6sLEMtj4NaTDsgE5FKpoQ
        $transaction = getTransactionByAddress($arg2);
        var_dump($transaction);
    break;
    default:
        var_dump("nothing to do");
}

function getTransactionByHash($hash) {
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://blockchain.info/rawtx/" . $hash,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            "Cookie: __cfduid=d8c2f0d52918dda848e3477e0bb8efc801587801023"
        ),        
        CURLOPT_SSL_VERIFYPEER =>  FALSE,
        CURLOPT_SSL_VERIFYHOST => FALSE,
    ));

    $response = curl_exec($curl);
    if ($response === false) echo "curl error: " . curl_error($curl) . "\n";
    curl_close($curl);
    
    return $response;
}

function getTransactionByAddress($address) {
    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://blockchain.info/rawaddr/" . $address,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            "Cookie: __cfduid=d8c2f0d52918dda848e3477e0bb8efc801587801023"
        ),
        CURLOPT_SSL_VERIFYPEER =>  FALSE,
        CURLOPT_SSL_VERIFYHOST => FALSE,
    ));

    $response = curl_exec($curl);
    if ($response === false) echo "curl error: " . curl_error($curl) . "\n";
    curl_close($curl);

    return $response;
}




function bitcoinApiList() {
    require_once('./lib/easybitcoin.php');
    $bitcoin = new Bitcoin('user','pass','192.168.1.218','8332');

    $blocknumber = $bitcoin->getblockcount();
    var_dump($blocknumber);

    $transaction = $bitcoin->getrawtransaction('0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098', 1);
    var_dump($transaction);

    $block = $bitcoin->getblock('000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f');
    var_dump($block);

    $balance = $bitcoin->getbalance();
    var_dump($balance);
}
